package webapicontroller

import (
	"encoding/json"
	"fmt"
	"net/http"
	"photoPlugIn/dbMethod"
	framework "photoPlugIn/webApiFramework"
	microcloud "photoPlugIn/webApiFramework"
	"strconv"
)

/**
 * r.PostFormValue  : 可以解析 Post/PUT Content-Type=application/x-www-form-urlencoded 或 Content-Type=multipart/form-data
 */

type UserConterller struct {
}

func (p *UserConterller) Router(router *framework.RouterHandler) {
	//设置路由
	router.Router("/photoApi/getPhoto", p.getPhoto)
	router.Router("/register", p.register)
	router.Router("/login", p.login)
	router.Router("/findAll", p.findAll)
}

//POST Content-Type=application/x-www-form-urlencoded
func (p *UserConterller) register(w http.ResponseWriter, r *http.Request) {
	fmt.Println("register-r", r)
	microcloud.ResultOk(w, "register success")
}

//POST Content-Type=application/x-www-form-urlencoded
func (p *UserConterller) login(w http.ResponseWriter, r *http.Request) {
	fmt.Println("/photoApi/getPhoto-r", r)

	microcloud.ResultOk(w, "login success")
}

//本webAPI使用唯一使用接口，使用POST ，暂未使用GET，没有实现获取GET参数的正则
func (p *UserConterller) getPhoto(w http.ResponseWriter, r *http.Request) {
	// fmt.Println("register-r", r)
	// fmt.Println("register-Method", r.Method)
	// fmt.Println("register-Body", r.Form.Get("dirID"))
	decoder := json.NewDecoder(r.Body)
	// fmt.Println("decoder", decoder)
	// 用于存放参数key=value数据
	var params map[string]string
	// 解析参数 存入map
	decoder.Decode(&params)

	dirID, err := strconv.ParseInt(params["dirID"], 10, 64)
	if err != nil {
		framework.ResultFail(w, "404")
	}
	//根据父ID查询文件夹
	dirList := dbmethod.GetPhotoDirs(dirID)
	//根据父ID查询照片
	photoList := dbmethod.GetPhotoLists(dirID)
	//定义接口的返回格式
	wdata := []dbmethod.SourcePhoto{}
	for _, value := range dirList {
		wdata = append(wdata, dbmethod.SourcePhoto{
			FileName:  value.DirName,
			PhotoName: value.DirAliasName,
			IsDir:     true,
			Id:        value.Id,
		})
	}
	for _, value := range photoList {
		wdata = append(wdata, dbmethod.SourcePhoto{
			FileName:  value.FileName,
			PhotoName: value.PhotoName,
			IsDir:     false,
			FileUrl:   "/photoDB/" + value.MD5 + ".jpg",
		})
	}
	// fmt.Println("dirList", wdata)
	framework.ResultJsonOk(w, wdata)
	// microcloud.ResultOk(w, "register success")
}

// GET/POST
func (p *UserConterller) findAll(w http.ResponseWriter, r *http.Request) {
	users := []string{"1", "2", "3", "4"}
	framework.ResultJsonOk(w, users)
}
